package com.example.zwh.computershop.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.zwh.computershop.R;
import com.example.zwh.computershop.handleDataClient.handleData;
import com.example.zwh.computershop.home.views.Goods;
import com.example.zwh.computershop.home.views.Goods_Home_Adapter;
import com.example.zwh.computershop.home.views.Home_search;
import com.example.zwh.computershop.particulars.particulars;
import com.example.zwh.computershop.sqlModel.Product;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


public class Home_Fragment extends Fragment {

    @BindView(R.id.ll_honme_search)
    LinearLayout llHonmeSearch;
    Unbinder unbinder;
    @BindView(R.id.lb_home_banner)
    Banner lbHomeBanner;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.res_home_good)
    RecyclerView resHomeGood;
    @BindView(R.id.ll_honme_search_name)
    LinearLayout llHonmeSearchName;
    @BindView(R.id.home_tv_search_text)
    TextView homeTvSearchText;

    //数据集合
    private List<Goods> mGoods = mGoods = new ArrayList<>();
    private String TAG = "Shenyutian";
    private int state;//线程用的
    //全部的商品数据
    private ArrayList<Product> mproducts = new ArrayList<>();
    //recyclerview 和 适配器的创建
    private RecyclerView rvRecyclerView;
    private Goods_Home_Adapter adapter;
    //广告的（轮播图）的集合
    private List<String> banner = new ArrayList<>();
    //banner中的数据
    private List<String> imageTitle_home_top = new ArrayList<>();//标题
    private List<String> imageName_home_top = new ArrayList<>();//图片

    //绘制图
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getPro();
        rv_adapter();
    }

    //rv 的使用
    private void rv_adapter() {
        //屏幕显示用于上面的轮播图一起跟着滑动
        final GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 10) {
            @Override
            public boolean canScrollVertically() {
                // 直接禁止垂直滑动
                return false;
            }
        };
        rvRecyclerView = getActivity().findViewById(R.id.res_home_good);
        rvRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //前面视图为一行5个 后面的是一行2个
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position < 10)
                    return 2;
                else
                    return 5;
            }
        });
        initbanner();
        rvRecyclerView.setLayoutManager(layoutManager);
        //利用这个来实现线程同步
        if(state == 3){
            mGoods.clear();
            initclass();
            initData();
            Goods_Home_Adapter adapter = new Goods_Home_Adapter(mGoods, getContext());
            rvRecyclerView.setAdapter(adapter);
        }
    }

    //加载banner轮播图数据 点击事件也有了
    private void initbanner() {

        if(imageName_home_top.size() <= 0) {
            imageTitle_home_top.add("联想ThinkPad翼480");
            imageName_home_top.add("https://p1.lefile.cn/fes/cms/2018/12/27/4twrshz3bxcqxy01gjbou34j30ldp5682014.jpeg");
            imageTitle_home_top.add("华硕(ASUS) 灵耀S 2代" );
            imageName_home_top.add("https://static.asus.com.cn/store/20181221/11453850505752.jpg");
            imageTitle_home_top.add("ThinkPad 联想" );
            imageName_home_top.add("https://p1.lefile.cn/product/adminweb/2018/12/01/3fd5b78c-0ad1-4de7-8403-df1e64f48d2b.jpg");
            imageTitle_home_top.add("戴尔DELL燃7000" );
            imageName_home_top.add("https://gdp.alicdn.com/imgextra/i4/379092568/O1CN01FRRNfs1UqBaJUgxJG_!!379092568.jpg");
        }

        //设置banner样式
        lbHomeBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        //设置图片加载器
        lbHomeBanner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        lbHomeBanner.setImages(imageName_home_top);
        //设置banner动画效果
        lbHomeBanner.setBannerAnimation(Transformer.RotateDown);
        //设置标题集合（当banner样式有显示title时）
        lbHomeBanner.setBannerTitles(imageTitle_home_top);
        //设置轮播时间
        lbHomeBanner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        lbHomeBanner.setIndicatorGravity(BannerConfig.CENTER);
        //图片点击事件
        OnBannerListener listener = new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Toast.makeText(getContext(), "点击图片"+imageTitle_home_top.get(position),Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getContext(), particulars.class);
                intent.putExtra("come_product",imageTitle_home_top.get(position));
                startActivity(intent);

            }
        };
        lbHomeBanner.setOnBannerListener(listener);
        //banner设置方法全部调用完毕时最后调用
        lbHomeBanner.start();

    }

    //加载第二个推荐栏数据
    private void initclass() {
//        for (int i = 0; i < 3; i++) {
//            mGoods.add(new Goods(2, R.drawable.home_art_collection, "品牌" + i));
//            mGoods.add(new Goods(2, R.drawable.home_art_collection, "分类" + i));
//        }
        mGoods.add(new Goods(2, R.drawable.xr_01, "联想Think"));
        mGoods.add(new Goods(2, R.drawable.xr_02, "苹果iMac"));
        mGoods.add(new Goods(2, R.drawable.xr_03, "苹果平版"));
        mGoods.add(new Goods(2, R.drawable.xr_04, "华硕xxx"));
        mGoods.add(new Goods(2, R.drawable.xr_05, "联想扬天"));
        mGoods.add(new Goods(2, R.drawable.xr_06, "航嘉电脑"));
        mGoods.add(new Goods(2, R.drawable.xr_07, "神舟z6"));
        mGoods.add(new Goods(2, R.drawable.xr_08, "HUAWEI"));
        mGoods.add(new Goods(2, R.drawable.xr_09, "惠普电脑"));
        mGoods.add(new Goods(2, R.drawable.xr_10, "不认识的"));
    }

    //输出视图
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    //主界面的点击事件
    @OnClick({R.id.ll_honme_search, R.id.ll_honme_search_name})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_honme_search:
//                Toast.makeText(getContext(), "打开搜索框", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getContext(), Home_search.class);
                startActivity(intent);
                break;
            case R.id.ll_honme_search_name:
                String inputText = homeTvSearchText.getText().toString();
//                Toast.makeText(getContext(), "点击搜索结果是:"+inputText, Toast.LENGTH_SHORT).show();
                Intent intent2 = new Intent(getContext(), Home_search.class);
                startActivity(intent2);
                break;
        }
    }

    //加载图片banner轮播图图片
    private class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            //Glide 加载图片简单用法
            Glide.with(context).load((String) path).into(imageView);
        }
    }

    //服务器拿数据了
    public void getPro() {
        Thread t = new Thread(new takeThread());
        t.start();
        try {
            t.join();
        }catch (InterruptedException ie) {
            ie.printStackTrace();
        }
    }
    //数据线程
    class takeThread extends Thread {
        @Override
        public void run() {
            state = handleData.getPro(mproducts);//拿数据的ArrayList类型数组mproducts
        }
    }

    /**
     * 加入第三个界面数据
     */
    private void initData() {
//        Log.d(TAG, "initData: ");
        //创建迭代器
        Iterator<Product> productIterator = mproducts.iterator();
        while(productIterator.hasNext()) {
            Product mproduct  = productIterator.next();
            //为了图片id
            int imageId = getImageID("R.drawable."+mproduct.getImgUrl());
            Goods good = new Goods(3, imageId, mproduct.getProductName(), mproduct.getPrice());
            mGoods.add(good);
        }
    }

    /**
     * 根据图片名字反射出图片ID
     * @return
     */
    public static int getImageID(String name){

        int id = R.drawable.p001;
        try {
//            Log.e("Shenyutian", "id:p001 "+id );
            int test = 0;
            test = Integer.valueOf(name.substring(name.length()-7, name.length()-4));
//            Log.e("Shenyutian", "test: "+test );
            id = id+test-1;
        } catch (Exception e) {
            id = R.drawable.p002;
            e.printStackTrace();
        }
//        Log.e("Shenyutian", "getImageID: "+id );
        return id;
    }

}
